﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using 天离安卓权限维持系统.Api;
using static 天离安卓权限维持系统.Form1;

namespace 天离安卓权限维持系统.Android_Form
{
    public partial class Listerner : Form
    {
        public Listerner()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(textBox1.Text) || string.IsNullOrEmpty(textBox2.Text) || string.IsNullOrEmpty(textBox3.Text))
                {
                    MessageBox.Show("数据不能为空，请输入！");
                }
                else
                {
                    string jsonFilePath = "listerner.json";

                    // 确保使用 Api.ListConfigApi.Listenner
                    Api.ListConfigApi.Listenner newListener = new Api.ListConfigApi.Listenner
                    {
                        id = GenerateRandomId(jsonFilePath),
                        listenIP = textBox1.Text,
                        listenPort = Convert.ToInt32(textBox2.Text),
                        // 默认为停止
                        listenStatus = "stop",
                        listenRemarks = textBox3.Text,
                        payload = comboBox1.Text
                    };

                    // 读取现有的 JSON 数据
                    var listenerList = Services.Json_Services.ReadJson(jsonFilePath);
                    if (listenerList == null)
                    {
                        listenerList = new Api.ListConfigApi.ListenerList { Listeners = new List<Api.ListConfigApi.Listenner>() };
                    }

                    // 添加新的 Listener
                    listenerList.Listeners.Add(newListener); // 这里应该没有问题

                    // 写回 JSON 文件
                    Services.Json_Services.WriteJson(jsonFilePath, listenerList);
                    MessageBox.Show("创建监听成功");
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("异常：" + ex.ToString());
            }
        }
        private static int GenerateRandomId(string jsonFilePath)
        {
            Random random = new Random();
            int newId;
            Api.ListConfigApi.ListenerList existingListeners = Services.Json_Services.ReadJson(jsonFilePath);
            HashSet<int> existingIds = new HashSet<int>();

            if (existingListeners != null)
            {
                foreach (var listener in existingListeners.Listeners)
                {
                    existingIds.Add(listener.id);
                }
            }

            // 生成一个不重复的随机 ID
            do
            {
                newId = random.Next(1, 10000); // 设定 ID 的范围
            } while (existingIds.Contains(newId));

            return newId;
        }

        private async void Listerner_Load(object sender, EventArgs e)
        {
            // 获取IP地址
            await Services.GetInterIp_Services.GetIp();
            string ip = Api.Public_Api.Ip.ToString();
            label6.Text = ip;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int portToCheck = Convert.ToInt32(textBox2.Text); // 要检查的端口

            try
            {
                if (IsPortInUse(portToCheck))
                {
                    MessageBox.Show("端口：" + portToCheck + " 被占用！", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                    MessageBox.Show("端口未被占用");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("检查端口时发生错误: " + ex.Message);
            }
        }
        static bool IsPortInUse(int port)
        {
            // 获取本地计算机的网络连接信息
            var tcpConnections = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections();
            var udpListeners = IPGlobalProperties.GetIPGlobalProperties().GetActiveUdpListeners();

            // 检查 TCP 连接
            if (tcpConnections.Any(c => c.LocalEndPoint.Port == port))
            {
                return true;
            }

            // 检查 UDP 监听
            if (udpListeners.Any(u => u.Port == port))
            {
                return true;
            }

            return false; // 如果都没有，返回 false
        }
    }
}
